package com.bawei.library_network.factory

import androidx.lifecycle.LiveData
import retrofit2.Call

import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import java.lang.reflect.Type
import java.util.concurrent.atomic.AtomicBoolean

/**

 * @Author : ytx

 * @Time : On 2023/5/20 08:20

 * @Description : LiveDataCallAdapter

 */
class LiveDataCallAdapter<R>(val observerType: Type) :CallAdapter<R,LiveData<R>> {
    override fun responseType(): Type {
        return observerType
    }
    //将okhttp返回call---livedata
    override fun adapt(call: Call<R>): LiveData<R> {
        return object : LiveData<R>() {
            //确保多线程情况下安全的运行，不会被其他线程打断，一直等到该方法执行完成，才由jvm从等待队列中选择其他线程进入
            private var started = AtomicBoolean(false)
            override fun onActive() {
                super.onActive()
                if (started.compareAndSet(false, true)) {
                    ///将okhttp返回call---livedata
                    call.enqueue(object : Callback<R> {
                        //成功
                        override fun onResponse(call: Call<R>, response: Response<R>) {
                            if(response.code() == 200){//成功
                                postValue(response.body())
                            }else{//失败
                                var apiResponse = ApiResponse(response.code(),response.message(),"")
                                postValue(apiResponse as R)//java中强转
                            }
                        }
                        //失败
                        override fun onFailure(call: Call<R>, t: Throwable) {
                            var apiResponse = ApiResponse(500,t.message.toString(),"")
                            postValue(apiResponse as R)//java中强转
                        }

                    })
                }

            }
        }

    }
}